# -*- coding: utf-8 -*-
import os ,subprocess,sys,winreg
import pandas as pd
from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from Batch_Submission_ui import Ui_Batch_Submission_Win
from PyQt6.QtCore import QThread, pyqtSignal,pyqtSignal, QObject


class FileProcessor(QThread):
    progressChanged = pyqtSignal(int)  # 定义一个进度信号

    def __init__(self,FliePath ,current_folder, file_list, maya_version):
        super().__init__()
        self.FliePath = FliePath
        self.current_folder =current_folder
        self.file_list = file_list
        self.maya_version = maya_version
    def run(self):
        # 文件处理逻辑
        for i, file_path in enumerate(self.file_list):
            # 处理文件
            batch_CheckPy = os.path.join(self.current_folder, "batch_Check.py").replace("\\", "/")
            cmd = self.maya_version + " -command \"python(\\\"execfile('"+ batch_CheckPy + "')\\\")\"  -file {}".format(file_path)
            proc = subprocess.Popen(cmd)#, creationflags=subprocess.CREATE_NO_WINDOW, stdout=subprocess.DEVNULL
            proc.wait()
            # 发出进度信号
            self.progressChanged.emit(i + 1)
        try:
            logPath = os.path.join(self.FliePath, "log")
            TxT_Log_Name = "log.txt"
            xlsx_Log_Name = "log.xlsx"
            TxT_Log = os.path.join(logPath, TxT_Log_Name).replace('\\', '/')
            xlsx_Log = os.path.join(logPath, xlsx_Log_Name).replace('\\', '/')
            file_name, file_extension = os.path.splitext(TxT_Log)
            if file_extension == ".txt":
                # 读取文本文件
                with open(TxT_Log, 'r', encoding='utf-8', errors='ignore') as file:
                    lines = file.readlines()
                # 拆分字段并创建 DataFrame
                data = []
                for line in lines:
                    parts = line.strip().split(',')
                    data.append(parts)
                max_length = max(len(row) for row in data)
                columns = []
                for i in range(1, max_length + 1):
                    columns.append("Column" + str(i))
                # 创建 DataFrame
                df = pd.DataFrame(data, columns=columns)
                # 创建 Excel writer 对象
                with pd.ExcelWriter(xlsx_Log, engine='openpyxl') as writer:
                    # 将数据写入 Excel 表格
                    df.to_excel(writer, index=False, sheet_name='Sheet1')
            # 读取 Excel 文件
            wb = load_workbook(xlsx_Log)
            # 选择工作表
            ws = wb['Sheet1']
            # 设置单元格样式
            green_fill = PatternFill(fill_type='solid', fgColor='00FF00')
            red_fill = PatternFill(fill_type='solid', fgColor='FF0000')
            # 遍历单元格并设置颜色
            for row in ws.iter_rows():
                for cell in row:
                    if cell.value and 'YES' in str(cell.value):
                        cell.fill = green_fill
                    if cell.value and 'NO' in str(cell.value):
                        cell.fill = red_fill

            # 保存修改
            wb.save(xlsx_Log)
        except:
            pass


class PIliangtijiao(Ui_Batch_Submission_Win, QMainWindow):
    def __init__(self):
        super(PIliangtijiao, self).__init__()
        self.setupUi(self)
        self.__ui__()
        self.process_thread = None
    def __ui__(self):
        # 获取当前文件所在的文件夹路径
        self.current_folder = os.path.dirname(os.path.abspath(__file__))
        os.environ['PYTHONPATH'] = os.path.join(self.current_folder, "CheckType")
        self.combobox()
        self.pushButton.clicked.connect(self.select_folder)
        self.pushButton_3.clicked.connect(self.start_processing)
        self.MayaVersion.currentIndexChanged.connect(lambda *args: self.get_selected_option())
    def start_processing(self):
        file_list = []
        self.progressBar.setValue(0)
        file_count = self.Flie_listWidget.count()
        self.progressBar.setMaximum(file_count)
        selected_option = self.get_selected_option()
        for i in range(self.Flie_listWidget.count()):
            item = self.Flie_listWidget.item(i)
            file_list.append(item.text())
        self.thread = FileProcessor(self.lineEdit.text(),self.current_folder,file_list, self.Set_MayaVersion().get(selected_option))
        self.thread.progressChanged.connect(self.update_progress)  # 连接进度信号与更新进度条的方法
        self.thread.start()
    def update_progress(self, value):
        self.progressBar.setValue(value)  # 更新进度条的值
    def combobox(self):
        items = (list(self.Set_MayaVersion().keys()))
        self.MayaVersion.addItems(items)
    def get_selected_option(self):
        selected_option = self.MayaVersion.currentText()
        return(selected_option)
    def select_folder(self):
        folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
        if len(folder_path):
            self.lineEdit.setText(folder_path)
            self.Flie_listWidget.clear()
            file_type = ['ma', 'mb']
            for file_name in os.listdir(folder_path):
                # 过滤文件夹，只添加文件
                if os.path.isfile(os.path.join(folder_path, file_name)):
                    file_path = os.path.join(folder_path, file_name)
                    file_path = file_path.replace('\\', '/')
                    if file_path.rsplit('.', 1)[-1] in file_type:
                        # 将文件名添加到列表控件
                        self.Flie_listWidget.addItem(file_path)
    def Set_MayaVersion(self):
        my_maya = {}
        for i in range(2008, 2025):
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,'SOFTWARE\\Autodesk\\Maya' + '\\' + str(i) + '\\' + 'Setup\\InstallPath')
                path = winreg.QueryValueEx(key, 'MAYA_INSTALL_LOCATION')
                if path[0]:
                    mayabatch = os.path.join(os.path.join(path[0], "bin"), "mayabatch.exe")
                    my_maya[str(i)] = mayabatch.replace('\\', '/')
            except:
                pass
        return (my_maya)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = PIliangtijiao()
    window.show()
    sys.exit(app.exec())